package com.cocos.game;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;

import android.util.Log;

import androidx.annotation.NonNull;

import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchaseHistoryRecord;
import com.android.billingclient.api.PurchaseHistoryResponseListener;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
import com.cocos.lib.CocosHelper;
import com.cocos.lib.CocosJavascriptJavaBridge;
import com.cocos.lib.GlobalObject;


import org.json.JSONException;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class GooglePay {

    public PurchasesUpdatedListener purchasesUpdatedListener = null;
    public BillingClient  mBillingClient = null;
    private Handler handler = new Handler();
    private final int consumeImmediately = 0;
    private final int consumeDelay = 1;

    private  boolean s_isConnectGooglePlay = false;
    private AppActivity mAppActivityRef = null;
    private Map<String, SkuDetails> skuDetailsMap = new HashMap();

    public static GooglePay Instance;

    public static GooglePay getInstance(){
        if(Instance==null){
            Instance = new GooglePay();
        }
        return Instance;
    }

    private Activity getAppActivity(){
        if( GlobalObject.getActivity() != null){
            return GlobalObject.getActivity();
        }
        else{
            return  (Activity)mAppActivityRef;
        }
    }

    /**
     * 初始化BillingClient
     */
    public void initBillingClient(AppActivity context) {
        mAppActivityRef = context;
        if(purchasesUpdatedListener==null){
            purchasesUpdatedListener = new PurchasesUpdatedListener() {
                @Override
                public void onPurchasesUpdated(@NonNull BillingResult billingResult, List<Purchase> purchases) {
                    // To be implemented in a later section.
                    //购买完成回调
                    if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchases != null) {
                        Log.e("TAG", "购买成功 ");
                        for (Purchase purchase : purchases) {
                            Log.e("TAG", "购买成功111 ");

                            handlePurchaseConsume(purchase);
                        }
                    } else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.USER_CANCELED) {
                        // Handle an error caused by a user cancelling the purchase flow.
                        Log.e("TAG", "购买失败，用户取消 ");
                        // 在GL线程运行
                        CocosHelper.runOnGameThread(new Runnable() {
                            @Override
                            public void run() {
                                String failReason = "USER_CANCELED";
                                String value = "NativeJSBridgeIns.onGooglePayFail(\"" + failReason + "\");";
                                System.out.println("evalstring: " + value);
                                CocosJavascriptJavaBridge.evalString(value);
                            }
                        });
                    } else {
                        // Handle any other error codes.
                        int iBillingResponseCode = billingResult.getResponseCode();
                        Log.e("TAG", "购买失败，ResponseCode " + iBillingResponseCode);
                        // 在GL线程运行
                        CocosHelper.runOnGameThread(new Runnable() {
                            @Override
                            public void run() {
                                @SuppressLint("DefaultLocale")
                                String failReason= String.format("fail，ResponseCode：%d",iBillingResponseCode);
                                String value = "NativeJSBridgeIns.onGooglePayFail(\"" + failReason + "\");";
                                System.out.println("evalstring: " + value);
                                CocosJavascriptJavaBridge.evalString(value);
                            }
                        });

                    }

                }
            };
        }
        if(mBillingClient==null){
            mBillingClient = BillingClient.newBuilder(getAppActivity())
                    .setListener(purchasesUpdatedListener)
                    .enablePendingPurchases()
                    .build();
        }

        startConnection();
    }
    /**
     * 连接到google
     */
    private void startConnection() {
        Log.e("TAG", "startConnection: 连接" );
        mBillingClient.startConnection(new BillingClientStateListener() {
            private BillingResult billingResult;

            @Override
            public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
                this.billingResult = billingResult;
                Log.e("TAG", "startConnection: 连接google成功111: " + billingResult.getResponseCode());
                //链接成功最好去查询订单，做掉单处理
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                    Log.e("TAG", "onBillingSetupFinished startConnection: 连接成功: ");
                    s_isConnectGooglePlay = true;
//                    querySkuDetailsAsync();
                    queryAndConsumePurchase();
                }
            }
            @Override
            public void onBillingServiceDisconnected() {
                Log.e("TAG", "onBillingSetupFinished startConnection: 连接失败: ");
                s_isConnectGooglePlay = false;
                startConnection();
            }
        });
    }

    /**
     * 查询应用内商品详细信息 并且返回给客户端显示价格
     */
    public void querySkuDetailsAsync() {
        Log.e("TAG", "GooglePay: ");
        List skuList = new ArrayList<>();
//        skuList.add("premium_upgrade");
//        skuList.add("gas");
        SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
        params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);//INAPP应用内支付

        mBillingClient.querySkuDetailsAsync(params.build(),new SkuDetailsResponseListener() {
            @Override
            public void onSkuDetailsResponse(@NonNull BillingResult billingResult, List<SkuDetails> skuDetailsList) {
//                int resultCode = billingResult.getResponseCode();
                // Process the result.
                Log.e("TAG", "onSkuDetailsResponse: "+billingResult );
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.SERVICE_DISCONNECTED) {
                    //未连接
                    s_isConnectGooglePlay = false;
                    return;
                }
                else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                    for(SkuDetails skuDetails : skuDetailsList)
                        if (!skuDetailsMap.containsKey(skuDetails.getSku())) {
                            skuDetailsMap.put(skuDetails.getSku(), skuDetails);
                        }
                }
            }
        });
    }

    /**
     * 购买商品
     */
    public void tryGooglePay(String iap_Id, String orderId) {
        Log.e("TAG", "GooglePay, iap_Id: " + iap_Id + "orderId:"+ orderId);


        List<String> skuList = new ArrayList<>();

        skuList.add(iap_Id);

        SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
        params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);

        GooglePay.getInstance().mBillingClient.querySkuDetailsAsync(params.build(), new SkuDetailsResponseListener() {
            @Override
            public void onSkuDetailsResponse(@NonNull BillingResult billingResult, List<SkuDetails> skuDetailsList) {

                Log.e("TAG", "billingResult " + billingResult.getResponseCode() );
                Log.e("TAG", "onSkuDetailsResponse: "+ skuDetailsList);

                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && skuDetailsList != null) {
                    Log.e("TAG", "启动购买 ");

                    for (SkuDetails skuDetails : skuDetailsList) {
//                        if (iap_Id.equals(skuDetails.getSku())) {
                        Log.e("TAG", "启动购买 " + skuDetails.getSku());

                        BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                                .setSkuDetails(skuDetails)
                                .setObfuscatedAccountId(orderId)
                                .build();
                        int responseCode = GooglePay.getInstance().mBillingClient.launchBillingFlow(getAppActivity(), flowParams).getResponseCode();
                        if (responseCode == BillingClient.BillingResponseCode.OK) {
                            Log.i("TAG", "成功启动google支付");
                        } else {
                            //BILLING_RESPONSE_RESULT_OK	0	成功
                            //BILLING_RESPONSE_RESULT_USER_CANCELED	1	用户按上一步或取消对话框
                            //BILLING_RESPONSE_RESULT_SERVICE_UNAVAILABLE	2	网络连接断开
                            //BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE	3	所请求的类型不支持 Google Play 结算服务 AIDL 版本
                            //BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE	4	请求的商品已不再出售
                            //BILLING_RESPONSE_RESULT_DEVELOPER_ERROR	5	提供给 API 的参数无效。此错误也可能说明应用未针对 Google Play 结算服务正确签名或设置，或者在其清单中缺少必要的权限。
                            //BILLING_RESPONSE_RESULT_ERROR	6	API 操作期间出现严重错误
                            //BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED	7	未能购买，因为已经拥有此商品
                            //BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED	8	未能消费，因为尚未拥有此商品
                            Log.i("TAG", "LaunchBillingFlow Fail,code=" + responseCode);
                        }

//                        }
                    }
                }
            }
        });
    }


    //消耗商品
    private void handlePurchaseConsume(Purchase purchase) {
        // Purchase retrieved from BillingClient#queryPurchasesAsync or your PurchasesUpdatedListener.
//         Purchase purchase = ...;
        // Verify the purchase.
        // Ensure entitlement was not already granted for this purchaseToken.
        // Grant entitlement to the user.

        ConsumeParams consumeParams = ConsumeParams.newBuilder()
                .setPurchaseToken(purchase.getPurchaseToken())
                .build();

        ConsumeResponseListener listener = new ConsumeResponseListener() {
            @Override
            public void onConsumeResponse(BillingResult billingResult, @NonNull String purchaseToken) {
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                    // Handle the success of the consume operation.
                    Log.e("TAG", "onConsumeResponse: "+purchaseToken );

                    // 在GL线程运行
                    CocosHelper.runOnGameThread(new Runnable() {
                        @Override
                        public void run() {
                            String value = "NativeJSBridgeIns.onGooglePaySuccess(\"" + purchaseToken + "\");";
                            System.out.println("evalstring: " + value);
                            CocosJavascriptJavaBridge.evalString(value);
                        }
                    });

                }
            }
        };

        mBillingClient.consumeAsync(consumeParams, listener);
    }
    //查询最近的购买交易，并消耗商品
    private void queryAndConsumePurchase() {
        //queryPurchases() 方法会使用 Google Play 商店应用的缓存，而不会发起网络请求
        GooglePay.getInstance().mBillingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP,
                new PurchaseHistoryResponseListener() {
                    @Override
                    public void onPurchaseHistoryResponse(@NonNull BillingResult billingResult,
                                                          List<PurchaseHistoryRecord> purchaseHistoryRecordList) {
                        {
                            if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchaseHistoryRecordList != null) {
                                for (PurchaseHistoryRecord purchaseHistoryRecord : purchaseHistoryRecordList) {
                                    // Process the result.
                                    //确认购买交易，不然三天后会退款给用户
                                    try {
                                        Purchase purchase = new Purchase(purchaseHistoryRecord.getOriginalJson(), purchaseHistoryRecord.getSignature());
                                        if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
                                            //消耗品 开始消耗
                                            handlePurchaseConsume(purchase);
                                            //确认购买交易
                                            if (!purchase.isAcknowledged()) {
                                                acknowledgePurchase(purchase);
                                            }
                                            //TODO：这里可以添加订单找回功能，防止变态用户付完钱就杀死App的这种
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                });
    }


    private void acknowledgePurchase(Purchase purchase) {
        // 创建 AcknowledgePurchaseParams.Builder 对象。
        AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
                        .setPurchaseToken(purchase.getPurchaseToken())
                        .build();

        // 使用 BillingClient 的 acknowledgePurchase 方法来确认购买。
        GooglePay.getInstance().mBillingClient.acknowledgePurchase(acknowledgePurchaseParams, new AcknowledgePurchaseResponseListener() {
            @Override
            public void onAcknowledgePurchaseResponse(@NonNull BillingResult billingResult) {
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                    // 购买确认成功后的逻辑处理
                    Log.d("PurchaseConfirmation", "Purchase acknowledged successfully.");
                    // 可以在这里更新应用状态，比如解锁内容或特性等。
                } else {
                    // 处理确认失败的情况
                    Log.e("PurchaseConfirmation", "Failed to acknowledge purchase: " + billingResult.getDebugMessage());
                    // 你可以根据需要决定是否通知用户或者重试确认操作。
                }
            }
        });
    }
}
